package starlingui.component.drag
{
	import starling.animation.Tween;
	import starling.core.Starling;
	import starling.display.Image;
	import starling.events.Event;
	import starling.textures.Texture;
	
	import starlingui.component.event.ProgressEvent;
	import starlingui.manager.TextureLoader;
	import starlingui.manager.TextureResource;
	
	/**
	 *  物品图标(物品图标有两层构成,一层背景,一层图标,
	 *  背景层对应了用户是否能具体操作此物品的视觉提示);
	 * @author crl
	 *
	 */
	public class AbsIcon extends Image
	{
		public var pivotCenter:Boolean;
		private var _state:int=1;
		public function AbsIcon(texture:Texture=null,pivotCenter:Boolean=true)
		{
			if(texture==null){
				texture=TextureResource.getTextureByKey("loading");
				if(texture==null)texture=TextureResource.getEmpty();
			}
			super(texture);
			
			if(pivotCenter){
				this.pivotX=texture.width>>1;
				this.pivotY=texture.height>>1;
			}
			this.pivotCenter=pivotCenter;
		}
		
		protected function completeHandle(event:Event):void{
			if(alpha){
				var oldAlpha:Number=this.alpha;
				this.alpha=0;
				this.tweenPropertys(["alpha"],[oldAlpha]);
			}
			_state=1;
			var textureLoader:TextureLoader=event.target as TextureLoader;
			textureLoader.removeEventListener(Event.COMPLETE,completeHandle);
			textureLoader.removeEventListener(ProgressEvent.PROGRESS,progressHandle);
			initTexture(textureLoader.texture);
			
			if(hasEventListener(event.type)){
				this.dispatchEvent(event);
			}
		}
		
		
		/**
		 * state 为1时有准备好了的状态 
		 * @return 
		 * 
		 */		
		public function get state():int{
			return _state;
		}
		
		
		/**
		 *  
		 * @param value
		 * 
		 */		
		protected function initTexture(value:Texture):void
		{
			texture=value;
			readjustSize();
			if(pivotCenter){
				this.pivotX=texture.width>>1;
				this.pivotY=texture.height>>1;
			}
		}
		
		public function load(url:String):void{
			var textureLoader:TextureLoader=TextureResource.getURL(url);
			if(textureLoader.isReady){
				initTexture(textureLoader.texture);
				return;
			}
			_state=0;
			textureLoader.addEventListener(Event.COMPLETE,completeHandle);
			textureLoader.addEventListener(ProgressEvent.PROGRESS,progressHandle);
		}
		
		protected function progressHandle(event:ProgressEvent):void{
			
		}
		
		private var propertysTween:Tween;
		public function tweenPropertys(propertys:Array,values:Array,time:Number=0.3):void{
			if(propertysTween==null){
				propertysTween=new Tween(this,time);
			}else{
				propertysTween.reset(this,time);
			}
			var len:int=propertys.length;
			for(var i:int=0;i<len;i++){
				propertysTween.animate(propertys[i],values[i]);
			}
			Starling.juggler.add(propertysTween);
		}
	}
}